package org.algorithm.biubiu.wheel_1.数组.二月;

/***
 * @author biubiu
 * @date 2022-03-02 星期三 19:22
 *
 *  给定一个数组， 求数组中和为给定target的最短子数组
 *
 * 输入：target = 7, nums = [2,3,1,2,4,3]
 * 输出：2
 * 解释：子数组 [4,3] 是该条件下的长度最小的子数组。
 *
 *  uri: https://leetcode-cn.com/problems/2VG8Kg/
 */
public class 最短子数组 {

    public static void main(String[] args) {
        int[] nums = {2,3,1,2,4,3};
        System.out.println(minSubArrayLen(7, nums));
    }

    public static int minSubArrayLen(int target, int[] nums) {
        if(nums==null||nums.length==0){
            return 0;
        }
        int start = 0;
        int end=0;
        int sum = 0;
        int res = Integer.MAX_VALUE;
        while(end<=nums.length-1){
            sum = sum + nums[end];
            while(sum>=target){
                res = Math.min(res,end-start+1);
                sum = sum-nums[start];
                start++;
            }
            end++;
        }
        return res==Integer.MAX_VALUE? 0:res;

    }
}
